<template>
  <div>
    <form class="card comment-form" @submit.prevent="addComment">
      <div class="card-block">
        <textarea v-model="comment.body" class="form-control" placeholder="Write a comment..." rows="3"></textarea>
      </div>
      <div class="card-footer">
        <img :src="user.avatar" class="comment-author-img" />
        <button class="btn btn-sm btn-primary" type="submit" :disabled="loading">
          Post Comment
        </button>
      </div>
    </form>

    <div class="card" v-for="comment in comments" :key="comment.id">
      <div class="card-block">
        <p class="card-text">{{ comment.body }}</p>
      </div>
      <div class="card-footer">
        <nuxt-link :to="{ name: 'profile', params: { username: comment.author.username } }" class="comment-author">
          <img :src="comment.author.image" class="comment-author-img" />
        </nuxt-link>

        <nuxt-link :to="{ name: 'profile', params: { username: comment.author.username } }" class="comment-author">
          {{ comment.author.username }}
        </nuxt-link>
        <span class="date-posted">{{ comment.createdAt | date('MMM DD, YYYY') }}</span>
      </div>
    </div>
  </div>
</template>

<script>
  import { getComments, addComment } from '@/api/article'
  import { mapState } from 'vuex'

	export default {
		name: 'ArticleComments',
    props: {
			article: {
				type: Object,
        required: true
      }
    },
    data () {
			return {
				comments: [],
        comment: {
          body: ''
        },
        loading: false,
      }
    },
    computed: {
      ...mapState({
        user: state => state.user
      })
    },
    mounted () {
			this.getComments()
    },
    methods: {
      async addComment() {
        const data = this.comment

        this.loading = true
        try {
          await addComment(this.article.slug, data)
          this.getComments()
          this.$set(this.comment, 'body', '')
          this.loading = false
        } catch (e) {
          this.loading = false
        }
        
      },
      async getComments() {
        const { data } = await getComments(this.article.slug)

        this.comments = data.comments
      }
    }
	}
</script>

<style lang='less' scoped>

</style>